import {fetchPost} from '../service/api';

export default {
  namespace: 'sys',

  state: {
    sysList: [],
  },

  effects: {
    *fetchSysList({payload}, {call, put}){
      const response = yield call(fetchPost, "querySys.do", payload);
      if(response){
        yield put({
          type: 'saveSysList',
          payload: response.list,
        });
      }
    },
    *addSys({payload}, {call, put}){
      const response = yield call(fetchPost, "addSys.do", payload);
      if(response){
        yield put({
          type: 'addSysItem',
          payload: Object.assign(payload, {id: response.id})
        });
      }
      return response;
    },
    *updateSys({payload}, { call, put }){
      const response = yield call(fetchPost, "updateSys.do", payload);
      if(response){
        yield put({
          type: 'updateSysItem',
          payload,
        });
      }
      return response;
    },
    *delSys({payload}, { call, put }){
      const response = yield call(fetchPost, "deleteSys.do", payload);
      if(response){
        yield put({
          type: 'deleteSysItem',
          payload,
        });
        return response;
      }
    },
  },

  reducers: {
    saveSysList(state, {payload}){
      return {
        ...state,
        sysList: payload,
      }
    },
    addSysItem(state, {payload}){
      return {
        ...state,
        sysList: state.sysList.concat([payload])
      }
    },
    updateSysItem(state, {payload}){
      return {
        ...state,
        sysList: state.sysList.map(item => {
          if(item.id === payload.id){
            return payload;
          }else{
            return item;
          }
        })
      }
    },
    deleteSysItem(state, {payload}){
      return {
        ...state,
        sysList: state.sysList.filter(item => item.id !== payload.id)
      }
    },
  },

  subscriptions: {
    init({ dispatch, history }){
      dispatch({
        type: 'fetchSysList',
        payload: {
          mode: "0"
        }
      });
    }
  }

}
